import socket, threading

class NetListener(threading.Thread):

    def __init__(self, port):
        self.addr = ("",port)
        self.data = []
        self.go = True
        threading.Thread.__init__(self)

    def run(self):
        print "NetListener thread started"
        s = socket.socket(socket.AF_INET,socket.SOCK_DGRAM)
        s.settimeout(5)
        s.bind(self.addr)

        while self.go:
                try:
                    data,addr = s.recvfrom(1024)
                    self.data.append(data.strip())
                except socket.timeout:
                    print "timeout waiting for data"
                    pass

        s.close()

    def get_data(self):
        if len(self.data) > 0:
            return self.data.pop(0)
        else:
            return False

    def stop(self):
        self.go = False

def net_send(ball, addr):
    data = "%s:%s:%s:%s:%s" % (ball.img_file, ball.x, ball.y, ball.dx, ball.dy)
    s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    s.sendto(data,addr)

if __name__ == "__main__":
    n = NetListener(42042)
    n.start()
    try:
        while 1:
            a = n.get_data()
            if a:
                (a,b,c,d,e) = a.split(":")
                print (a,b,c,d,e)
    except KeyboardInterrupt:
        pass
    except ValueError, e:
        print e
    n.stop()
    n.join(1)
